package com.gitee.easyopen.jwt.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gitee.easyopen.ApiConfig;
import com.gitee.easyopen.jwt.JwtService;
import com.gitee.easyopen.message.Errors;

public class JwtServiceImpl implements JwtService {
    private static Logger logger = LoggerFactory.getLogger(JwtServiceImpl.class);
    
    private static String secret = "#56gu25@41tCVr]>0$";

    private static Map<String, Object> headerClaims = new HashMap<>();
    static {
        headerClaims.put("typ", "JWT");
        headerClaims.put("alg", "HS256");
    }
    
    private ApiConfig apiConfig;
    
    public JwtServiceImpl() {
        super();
    }
    
    public JwtServiceImpl(ApiConfig apiConfig) {
        super();
        this.apiConfig = apiConfig;
    }

    @Override
    public String createJWT(Map<String, String> data) {
        Assert.notNull(apiConfig, "apiConfig尚未初始化");
        Builder builder = JWT.create().withHeader(headerClaims);
        Set<Entry<String, String>> entrySet = data.entrySet();
        for (Entry<String, String> entry : entrySet) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }

        Calendar expiredTime = Calendar.getInstance();
        expiredTime.add(Calendar.SECOND, apiConfig.getJwtExpireIn());

        try {
            return builder.withExpiresAt(expiredTime.getTime()) // 过期时间
                    .withIssuedAt(new Date()) // 创建时间
                    .sign(Algorithm.HMAC256(secret));// 签名
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw Errors.ERROR_OPT_JWT.getException();
        }
    }

    @Override
    public Map<String, Claim> verfiyJWT(String token) {
        JWTVerifier verifier = null;
        try {
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw Errors.ERROR_OPT_JWT.getException();
        }

        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw Errors.ERROR_JWT.getException();
        }

        return jwt.getClaims();
    }

    @Override
    public ApiConfig getApiConfig() {
        return apiConfig;
    }

    @Override
    public void setApiConfig(ApiConfig apiConfig) {
        this.apiConfig = apiConfig;
    }
    
}
